package util

import (
	"encoding/json"
	"errors"
	"io"
	"mime/multipart"
	"net"
	"os"
	"reflect"
)

/**
用于结构体转map，map转结构体，json转结构体，结构体数据转移
 **/
func StructTo(old interface{}, new interface{}) error {
	tp := reflect.TypeOf(old)
	var bt []byte
	var err error
	if tp.Name() == "string" {
		bt = []byte(old.(string))
	} else {
		bt, err = json.Marshal(old)
		if err != nil {
			return err
		}
	}
	err = json.Unmarshal(bt, new)
	if err != nil {
		return err
	}
	return nil
}

func Upload(host, dir string, file *multipart.FileHeader) (string, error) {
	now, err := os.Getwd()
	if err != nil {
		return "", err
	}
	dir = now + dir
	err = os.MkdirAll(dir, os.ModePerm)
	if err != nil {
		return "", err
	}
	fileName := dir + file.Filename
	f, err := os.Create(fileName)
	if err != nil {
		return "", err
	}
	defer f.Close()
	open, err := file.Open()
	if err != nil {
		return "", err
	}
	_, err = io.Copy(f, open)
	if err != nil {
		return "", err
	}

	url := host + fileName
	return url, nil
}

func GetIpAddress() (string, error) {
	netInterfaces, err := net.Interfaces()
	if err != nil {
		return "", err
	}
	for i := 0; i < len(netInterfaces); i++ {
		if (netInterfaces[i].Flags & net.FlagUp) != 0 {
			address, _ := netInterfaces[i].Addrs()

			for _, element := range address {
				if ipNet, ok := element.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
					if ipNet.IP.To4() != nil {
						return ipNet.IP.String(), nil
					}
				}
			}
		}
	}

	return "", errors.New("get ip fail")
}
